package com.example.demo;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;


@RestController
public class LoginController {

    @Resource
    Configuration cfg;

    @Autowired
    private UserDao userDao;

    @GetMapping(value = "/index")
    public String show() {

        User user = new User();
        user.setUserName("123");
        user.setPassWord("123");

        userDao.save(user);
        return "login success";
    }

    @GetMapping(value = "/freeMarker")
    public String freeMarker(Model model ) {

        model.addAttribute("title","标题");
        model.addAttribute("text","正文");

        freeMarkerContent(model);
        return "生成成功";
    }



    private void freeMarkerContent(Model model){
        try {
            Template temp = cfg.getTemplate("index.ftl");
            //以classpath下面的static目录作为静态页面的存储目录，同时命名生成的静态html文件名称
            File path = new File("d:/static/index.html");
            Writer file = new FileWriter(path);
            temp.process(model, file);
            file.flush();
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
